package com.xiaoxi.open.design.behavioral.chainofresponsibilitypattern.service.password;

import com.xiaoxi.open.design.behavioral.chainofresponsibilitypattern.domain.password.CheckResult;
import lombok.Data;

/**
 * @Author xiaoxi
 * @ProjectName chain_of_responsibility_pattern
 * @PackageName com.xiaoxi.open.design.behavioral.chainofresponsibilitypattern.service.password
 * @ClassName AbstractCheckPassword
 * @Description TODO
 * @Date 2024/4/24 16:53
 * @Version 1.0
 */
@Data
public abstract class AbstractCheckPassword {

    /**
     * 下一个节点
     */
    protected AbstractCheckPassword next = null;

    /**
     * 执行责任链
     *
     * @param checkResult
     * @throws Exception
     */
    public void execute(String password, CheckResult checkResult) throws Exception {

        // 执行当前阶段
        doHandler(password, checkResult);

        // 判断是否还有下个责任链节点，没有的话，说明已经是最后一个节点
        if (this.next != null) {
            this.next.execute(password, checkResult);
        }

        // 格式化数据
        recheckResult(checkResult);
    }

    /**
     * 通过 每一系列检查的结果 找到准确错误
     *
     * @param checkResult
     */
    private void recheckResult(CheckResult checkResult) {

        StringBuilder stringBuilder = new StringBuilder();
        int i;
        if (checkResult.getErrorReason().size() > 0) {
            for (i = 0; i < checkResult.getErrorReason().size(); ++i) {
                if (stringBuilder.length() > 0) {
                    stringBuilder.append(",");
                }

                stringBuilder.append(checkResult.getErrorReason().get(i));
            }
        }

        if (checkResult.getConfirmInfo().size() != 0) {

            if (stringBuilder.length() > 0) {
                stringBuilder.append(",");
            }
            stringBuilder.append("密码应包含");
            for (i = 0; i < checkResult.getConfirmInfo().size(); ++i) {
                stringBuilder.append(checkResult.getConfirmInfo().get(i));
                if (i < checkResult.getConfirmInfo().size() - 1) {
                    stringBuilder.append("、");
                }
            }
        }

        if (stringBuilder.length() > 0) {
            checkResult.setConclusion(stringBuilder.toString());
        } else {
            checkResult.setConclusion("");
        }

    }

    public abstract void doHandler(String password, CheckResult checkResult) throws Exception;

    /**
     * builder 责任链
     */
    public static class Builder {

        private AbstractCheckPassword head;
        private AbstractCheckPassword tail;

        public Builder addHandler(AbstractCheckPassword handler) {
            if (this.head == null) {
                // head用于保存游标
                this.head = handler;
            } else {
                this.tail.setNext(handler);
            }
            // tail 为游标，地址下指，下指
            this.tail = handler;
            return this;
        }

        public AbstractCheckPassword build() {
            return this.head;
        }
    }

}
